const { Controller } = require('egg');
const Response = require('../utils/response');

class UserController extends Controller {
  // 注册
  async register() {
    const { ctx, service } = this;
    const { name, password, email, phone } = ctx.request.body;

    if (!name || !password) {
      ctx.body = Response.error(400, '用户名和密码不能为空');
      return;
    }

    ctx.body = await service.user.register({
      name,
      password,
      email,
      phone,
    });
  }

  // 登录
  async login() {
    const { ctx, service } = this;
    const { username, password } = ctx.request.body;
    if (!username || !password) {
      ctx.body = Response.error(400, '用户名和密码不能为空');
      return;
    }
    ctx.body = await service.user.login(username, password);
  }

  // 修改密码
  async changePassword() {
    const { ctx, service } = this;
    const { oldPassword, newPassword } = ctx.request.body;
    const userId = ctx.state.user.id; // 从token中获取用户ID

    if (!oldPassword || !newPassword) {
      ctx.body = Response.error(400, '旧密码和新密码不能为空');
      return;
    }

    if (newPassword.length < 6) {
      ctx.body = Response.error(400, '新密码长度不能少于6位');
      return;
    }

    ctx.body = await service.user.changePassword(userId, oldPassword, newPassword);
  }
}
module.exports = UserController;